<template>
	<el-dialog
        v-model="visible"
        :title="!dataForm.id ? '新增' : '修改'"
        :close-on-click-modal="false"
        draggable>
		<el-form
            ref="dataFormRef"
            :model="dataForm"
            :rules="dataRules"
            label-width="120px"
            @keyup.enter="onSubmit()">
			<el-form-item
                prop="username"
                label="用户名">
				<el-input
                    v-model="dataForm.username"
                    placeholder="用户名">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="realName"
                label="姓名">
				<el-input
                    v-model="dataForm.realName"
                    placeholder="姓名">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="orgId"
                label="所属机构">
				<el-tree-select
					v-model="dataForm.orgId"
					:data="orgList"
					value-key="id"
					check-strictly
					:render-after-expand="false"
					:props="{ label: 'name', children: 'children' }"
					style="width: 100%"
					placeholder="请选择所属机构"
				/>
			</el-form-item>
			<el-form-item
                prop="gender"
                label="性别">
				<el-radio-group v-model="dataForm.gender">
                    <el-radio :value="0">男</el-radio>
                    <el-radio :value="1">女</el-radio>
                </el-radio-group>
			</el-form-item>
			<el-form-item
                prop="mobile"
                label="手机号">
				<el-input
                    v-model="dataForm.mobile"
                    placeholder="手机号">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="email"
                label="邮箱">
				<el-input
                    v-model="dataForm.email"
                    placeholder="邮箱">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="password"
                label="密码">
				<el-input
                    v-model="dataForm.password"
                    type="password"
                    placeholder="密码">
                </el-input>
			</el-form-item>
			<el-form-item
                prop="roleIdList"
                label="所属角色">
				<el-select
                    multiple
                    v-model="dataForm.roleIdList"
                    placeholder="所属角色"
                    style="width: 100%">
					<el-option
                        v-for="role in roleList"
                        :key="role.id"
                        :label="role.name"
                        :value="role.id">
                    </el-option>
				</el-select>
			</el-form-item>
			<el-form-item
                prop="postIdList"
                label="所属岗位">
				<el-select
                    multiple
                    v-model="dataForm.postIdList"
                    placeholder="所属岗位"
                    style="width: 100%">
					<el-option
                        v-for="post in postList"
                        :key="post.id"
                        :label="post.postName"
                        :value="post.id">
                    </el-option>
				</el-select>
			</el-form-item>
			<el-form-item
                prop="status"
                label="状态">
				<el-radio-group v-model="dataForm.status">
                    <el-radio :value="1">正常</el-radio>
                    <el-radio :value="0">停用</el-radio>
                </el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="onSubmit()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { userStore } from '@/store/user'
import { orgStore } from '@/store/org'
import { roleStore } from '@/store/role'
import { postStore } from '@/store/post'

const emit = defineEmits(['refresh'])
const useUserStore = userStore()
const useOrgStore = orgStore()
const useRoleStore = roleStore()
const usePostStore = postStore()

const visible = ref(false)
const postList = ref([])
const roleList = ref([])
const orgList = ref([])
const dataFormRef = ref(null)

const dataForm = reactive({
  id: 0,
  username: '',
  realName: '',
  orgId: '',
  orgName: '',
  password: '',
  gender: 0,
  email: '',
  mobile: '',
  roleIdList: [],
  postIdList: [],
  status: 1
})

const init = (id) => {
  visible.value = true
//   dataForm.id = 0
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
  }  

  getOrgList()
  getPostList()
  getRoleList()

  if (id) {
    // 加载用户信息
    getUser(id)
  } else {
    // 重置表单
    dataForm.id = 0
    dataForm.username = ''
    dataForm.realName = ''
    dataForm.orgId = ''
    dataForm.orgName = ''
    dataForm.password = ''
    dataForm.gender = 0
    dataForm.email = ''
    dataForm.mobile = ''
    dataForm.roleIdList = []
    dataForm.postIdList = []
    dataForm.status = 1
  }
}

const getUser = async (id) => {
  try {
    const res = await useUserStore.getUserOne(id)
    // console.log('获取用户信息:', res)
    Object.assign(dataForm, res)
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const getOrgList = async () => {
  try {
    const res = await useOrgStore.getOrgList()
    // console.log('获取机构列表:', [...res])
    orgList.value = res
  } catch (error) {
    console.error('获取机构列表失败:', error)
  }
}

const getPostList = async () => {
  try {
    const res = await usePostStore.getPostPage()
    // console.log('获取岗位列表:', res.list)
    postList.value = res.list
  } catch (error) {
    console.error('获取岗位列表失败:', error)
  }
}

const getRoleList = async () => {
  try {
    const res = await useRoleStore.getRolePage()
    // console.log('获取角色列表:', res.list)
    roleList.value = res.list
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

const dataRules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, max: 20, message: '字符个数在4-20之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '请检查手机号位数', trigger: 'blur' }
  ],
  orgId: [
    { required: true, message: '必填项不能为空', trigger: 'blur' }
]
}

// 提交表单数据
const onSubmit = async() => {
    if (!dataFormRef.value) return
    
    await dataFormRef.value.validate(async valid => {
        if (valid) {
            try {
                if (dataForm.id > 0) {
                    await useUserStore.updateUser(dataForm)
                } else {
                    await useUserStore.addUser(dataForm)
                }
                ElMessage.success('操作成功') // 提示成功信息
                visible.value = false // 关闭弹窗
                emit('refresh') // 刷新列表
            } catch (error) {
                console.error('提交表单数据失败:', error)
                ElMessage.error(error.message || '操作失败')
            }
        } else {
            ElMessage.error('请输入正确的信息') 
        }
    })
}

defineExpose({ init })
</script>

<style lang="scss" scoped>

</style>